package best.driver.android.Utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.provider.Settings;
import best.driver.android.BestApp;
import best.driver.android.R;
import best.driver.android.Utils.actions.Action1;
import best.driver.android.View.BestAlertDialogBase;

public class GPSUtils {

    public static final int STATE_OK = 1;
    public static final int STATE_SETTING = 0;
    public static final int STATE_CANCEL = 1;

    public static Dialog checkLocationAvailable(Activity activity, Action1<Integer> callback) {
        if (!isLocationEnable()) {
            return updateLocationSettings(activity, callback);
        }
        if (callback != null) {
            callback.run(STATE_OK);
        }
        return null;
    }

    private static Dialog updateLocationSettings(Activity activity, final Action1<Integer> callback) {
        if (activity == null) {
            return null;
        }
        BestAlertDialogBase dialog = DialogUtil.alert(
                activity,
                null,
                "请打开GPS定位哦，以免影响接单",
                "去设置",
                null,
                new BestAlertDialogBase.BestAlertDialogOnClickListener() {
                    @Override
                    public boolean onClick(BestAlertDialogBase dialog, int button) {
                        if (button == BestAlertDialogBase.BUTTON_OK) {
                            if (callback != null) {
                                callback.run(STATE_SETTING);
                            }
                            final Intent intent = new Intent("android.settings.LOCATION_SOURCE_SETTINGS");
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            BestApp.getInstance().startActivity(intent);
                        }
                        return false;
                    }
                });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                if (callback != null) {
                    callback.run(STATE_CANCEL);
                }
            }
        });
        return dialog;
    }

    public static boolean isGPSEnable() {
        String str = Settings.Secure.getString(BestApp.getInstance().getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return str != null && str.contains("gps");
    }

    public static boolean isNetworkLocationEnable() {
        String str = Settings.Secure.getString(BestApp.getInstance().getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return str != null && str.contains("network");
    }

    public static boolean isLocationEnable() {
        return isGPSEnable();
    }
}
